package com.meilai.project.service.finance.reimburse.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.finance.reimburse.ReimburseApplyCheckDTO;
import com.meilai.project.dto.finance.reimburse.ReimburseApplyDTO;
import com.meilai.project.dto.finance.reimburse.ReimburseApplyListDTO;
import com.meilai.project.dto.workflow.FlowBusinessDataSuperEntity;
import com.meilai.project.dto.workflow.WorkFlowCheckDTO;
import com.meilai.project.entity.finance.reimburse.*;
import com.meilai.project.entity.system.Dictionary;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.reimburse.ReimburseApplyMapper;
import com.meilai.project.service.finance.reimburse.*;
import com.meilai.project.service.system.DictionaryService;
import com.meilai.project.service.system.impl.UserServiceImpl;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.util.WorkFlowUtil;
import com.meilai.project.vo.finance.reimburse.ReimburseApplyVO;
import com.meilai.project.vo.system.UserForWFVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-12-07
 */
@Service
public class ReimburseApplyServiceImpl extends ServiceImpl<ReimburseApplyMapper, ReimburseApply> implements ReimburseApplyService {

    @Autowired
    private ReimburseApplyDetailService reimburseApplyDetailService;

    @Autowired
    private ReimbursePrivateDetailService reimbursePrivateDetailService;

    @Autowired
    private ReimbursePublicDetailService reimbursePublicDetailService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ReimburseApplyAttachmentService reimburseApplyAttachmentService;

    @Override
    public Page<ReimburseApplyVO> selectPageList(ReimburseApplyListDTO searchDTO) {
        Page<ReimburseApplyVO> page = searchDTO.createPage(ReimburseApplyVO.class);
        List<ReimburseApplyVO> listResult = baseMapper.selectPageList(page, searchDTO);
        page.setRecords(listResult);
        return page;
    }

    @Override
    public ReimburseApplyVO getOneById(Long id) {
        ReimburseApplyVO result = baseMapper.getOneById(id);
        if (result == null) throw new CommonException("数据不存在！");
        if (null != id) {
            Long userId = ThreadLocalUserUtil.get().getId();
            Boolean canCheck = WorkFlowUtil.canCheckData(userId, result);
            result.setCan_check(canCheck);
            result.setIs_applyer(userId.equals(result.getFlow_applyer_id()));
        } else {
            result.setIs_applyer(true);
        }
        // 处理子表数据
        result.setReimburseApplyDetailList(reimburseApplyDetailService.list(Wrappers.<ReimburseApplyDetail>lambdaQuery().eq(ReimburseApplyDetail::getReimburse_apply_id, result.getId())));
        result.setReimbursePrivateDetailList(reimbursePrivateDetailService.list(Wrappers.<ReimbursePrivateDetail>lambdaQuery().eq(ReimbursePrivateDetail::getReimburse_apply_id, result.getId())));
        result.setReimbursePublicDetailList(reimbursePublicDetailService.list(Wrappers.<ReimbursePublicDetail>lambdaQuery().eq(ReimbursePublicDetail::getReimburse_apply_id, result.getId())));
        result.setReimburseApplyAttachmentList(reimburseApplyAttachmentService.list(Wrappers.<ReimburseApplyAttachment>lambdaQuery().eq(ReimburseApplyAttachment::getReimburse_apply_id, result.getId())));
        // 获取字典数据
        Map<Long, Dictionary> dictionaryMap = dictionaryService.listByCode("bxxg-lm").stream().collect(Collectors.toMap(Dictionary::getId, Function.identity()));
        result.getReimburseApplyDetailList().forEach(item -> {
            Dictionary dictionary = dictionaryMap.get(item.getCategory_id());
            if (dictionary != null) {
                item.setCategory_name(dictionary.getName());
            } else {
                item.setCategory_name("未知类型");
            }

        });
        return result;
    }

    @Override
    public List<ReimburseApplyVO> getListBySaleIds(List<Long> sale_ids) {
        if (CollectionUtils.isEmpty(sale_ids)) {
            sale_ids.add(-1L);
        }
        List<ReimburseApplyVO> list = baseMapper.getListBySaleIds(sale_ids);
        if (CollectionUtils.isNotEmpty(list)) {
            handle(list);
        }
        return list;
    }

    @Override
    public List<ReimburseApplyVO> getListByContractIds(List<Long> contract_ids) {
        if (CollectionUtils.isEmpty(contract_ids)) {
            contract_ids.add(-1L);
        }
        List<ReimburseApplyVO> list = baseMapper.getListByContractIds(contract_ids);
        if (CollectionUtils.isNotEmpty(list)) {
            handle(list);
        }
        return list;
    }

    private void handle(List<ReimburseApplyVO> list) {
        List<Long> ids = list.stream().map(ReimburseApply::getId).collect(Collectors.toList());
        if (ids.isEmpty()) {
            ids.add(-1L);
        }
        // 获取字典数据
        Map<Long, Dictionary> dictionaryMap = dictionaryService.listByCode("bxxg-lm").stream().collect(Collectors.toMap(Dictionary::getId, Function.identity()));
        // 处理子表数据
        Map<Long, List<ReimburseApplyDetail>> reimburseApplyDetailMap = reimburseApplyDetailService.list(Wrappers.<ReimburseApplyDetail>lambdaQuery().in(ReimburseApplyDetail::getReimburse_apply_id, ids)).stream().collect(Collectors.groupingBy(ReimburseApplyDetail::getReimburse_apply_id));
        Map<Long, List<ReimbursePrivateDetail>> reimbursePrivateDetailMap = reimbursePrivateDetailService.list(Wrappers.<ReimbursePrivateDetail>lambdaQuery().in(ReimbursePrivateDetail::getReimburse_apply_id, ids)).stream().collect(Collectors.groupingBy(ReimbursePrivateDetail::getReimburse_apply_id));
        Map<Long, List<ReimbursePublicDetail>> reimbursePublicDetailMap = reimbursePublicDetailService.list(Wrappers.<ReimbursePublicDetail>lambdaQuery().in(ReimbursePublicDetail::getReimburse_apply_id, ids)).stream().collect(Collectors.groupingBy(ReimbursePublicDetail::getReimburse_apply_id));
        Map<Long, List<ReimburseApplyAttachment>> reimburseApplyAttachmentMap = reimburseApplyAttachmentService.list(Wrappers.<ReimburseApplyAttachment>lambdaQuery().in(ReimburseApplyAttachment::getReimburse_apply_id, ids)).stream().collect(Collectors.groupingBy(ReimburseApplyAttachment::getReimburse_apply_id));
        for (ReimburseApplyVO result : list) {
            List defaultValue = new ArrayList<>();
            result.setReimburseApplyDetailList(reimburseApplyDetailMap.getOrDefault(result.getId(), defaultValue));
            result.setReimbursePrivateDetailList(reimbursePrivateDetailMap.getOrDefault(result.getId(), defaultValue));
            result.setReimbursePublicDetailList(reimbursePublicDetailMap.getOrDefault(result.getId(), defaultValue));
            result.setReimburseApplyAttachmentList(reimburseApplyAttachmentMap.getOrDefault(result.getId(), defaultValue));
            result.getReimburseApplyDetailList().forEach(item -> {
                Dictionary dictionary = dictionaryMap.get(item.getCategory_id());
                if (dictionary != null) {
                    item.setCategory_name(dictionary.getName());
                } else {
                    item.setCategory_name("未知类型");
                }

            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(ReimburseApplyDTO dto) {
        int flowResult = saveAndBegin(dto, true);
        if (flowResult != 1) throw new CommonException("保存至草稿箱失败，请联系管理员！");
        else return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean begin(ReimburseApplyDTO dto) {
        // 提交
        int flowResult = saveAndBegin(dto, false);
        if (flowResult == 1) {
            // 仍在流程中
            return true;
        } else if (flowResult == 2) {
            // 无审批节点，直接结束
            return true;
        } else {
            throw new CommonException("提交失败，请联系管理员！");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean pass(ReimburseApplyCheckDTO dto) {
        // 通过
        int flowResult = passAndBack(dto, true, false);
        if (flowResult == 1) {
            // 通过后仍然在流程中
            return true;
        } else if (flowResult == 2) {
            // 审核后流程结束
            return true;
        } else {
            throw new CommonException("通过失败，请联系管理员！");
        }
    }

    private int saveAndBegin(ReimburseApplyDTO dto, boolean isSave) {
        // 获取当前人的id和部门id
        UserForWFVO user = UserServiceImpl.getUserForWF(dto);
        ReimburseApply temp = new ReimburseApply();
        BeanUtils.copyProperties(dto, temp);
        temp.setSubmit_time(LocalDate.now());

        // 设置流程字段，flow_type请自行对应“dict_flow_type”表中的id， 比如当前入职流程（考察登记流程）的id是5
        String flow_title = temp.getName() + "报销申请"; // 审批流程的名称，需要根据实际业务自行确定
        FlowBusinessDataSuperEntity fbdse = WorkFlowUtil.getStartSuperDataEntity(
                user.getUser_id(),  // 当前用户id
                user.getDep_id(), // 提交的部门id
                14, // 流程类型id，“dict_flow_type”表中的id
                flow_title // 自定义的流程标题
        );
        BeanUtils.copyProperties(fbdse, temp);

        // 是否为新数据
        // 新数据时，前端不传业务数据id
        // 非新数据时，即来源是“草稿箱”、“已删除”、“被退回”时，前端需要传入业务数据id
        boolean isFirst = (dto.getId() == null);

        // 由于流程字段含有id，会覆盖数据，此处需要手动setId
        if (!isFirst) temp.setId(dto.getId());

        boolean flag = isFirst ? save(temp) : updateById(temp);

        // 保存或者提交成功 插入字表数据
        // 删除旧的
        reimburseApplyDetailService.remove(Wrappers.<ReimburseApplyDetail>lambdaQuery().eq(ReimburseApplyDetail::getReimburse_apply_id, temp.getId()));
        reimbursePrivateDetailService.remove(Wrappers.<ReimbursePrivateDetail>lambdaQuery().eq(ReimbursePrivateDetail::getReimburse_apply_id, temp.getId()));
        reimbursePublicDetailService.remove(Wrappers.<ReimbursePublicDetail>lambdaQuery().eq(ReimbursePublicDetail::getReimburse_apply_id, temp.getId()));
        reimburseApplyAttachmentService.remove(Wrappers.<ReimburseApplyAttachment>lambdaQuery().eq(ReimburseApplyAttachment::getReimburse_apply_id, temp.getId()));
        // 保存新的
        if (CollectionUtils.isNotEmpty(dto.getReimburseApplyDetailList())) {
            dto.getReimburseApplyDetailList().forEach(item -> {
                item.setId(null);
                item.setReimburse_apply_id(temp.getId());
            });
            reimburseApplyDetailService.saveBatch(dto.getReimburseApplyDetailList());
        }
        if (CollectionUtils.isNotEmpty(dto.getReimbursePrivateDetailList())) {
            dto.getReimbursePrivateDetailList().forEach(item -> {
                item.setId(null);
                item.setReimburse_apply_id(temp.getId());
            });
            reimbursePrivateDetailService.saveBatch(dto.getReimbursePrivateDetailList());
        }
        if (CollectionUtils.isNotEmpty(dto.getReimbursePublicDetailList())) {
            dto.getReimbursePublicDetailList().forEach(item -> {
                item.setId(null);
                item.setReimburse_apply_id(temp.getId());
            });
            reimbursePublicDetailService.saveBatch(dto.getReimbursePublicDetailList());
        }

        if (CollectionUtils.isNotEmpty(dto.getReimburseApplyAttachmentList())) {
            dto.getReimburseApplyAttachmentList().forEach(item -> {
                item.setId(null);
                item.setReimburse_apply_id(temp.getId());
            });
            reimburseApplyAttachmentService.saveBatch(dto.getReimburseApplyAttachmentList());
        }
        if (!flag) throw new CommonException("保存失败");

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<ReimburseApply, ReimburseApplyMapper>(temp.getId(), user.getUser_id(), ReimburseApply.class);

        // 审批流程id
        // 新数据,传0L
        // 非新数据,根据数据id,查找wfData_id
        Long wfData_id = isFirst ? 0L : wfu.getWfDataId(dto.getId());
        // 旧数据记录留存
        ReimburseApply old_data = isFirst ? new ReimburseApply() : temp;

        return isSave ? wfu.SaveDraft(wfData_id) : wfu.Begin(wfData_id, "", old_data);
    }

    private int passAndBack(ReimburseApplyCheckDTO dto, boolean isPass, boolean... updateData) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        // 若业务数据有审批中可修改的内容，请自行更新
        if (updateData != null && updateData[0]) {
            ReimburseApply updateTemp = new ReimburseApply();
            BeanUtils.copyProperties(dto, updateTemp);
            updateById(updateTemp);
        }

        // 业务数据
        ReimburseApply temp = getById(dto.getId());

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<ReimburseApply, ReimburseApplyMapper>(dto.getId(), userId, ReimburseApply.class);

        // 审批入参类
        WorkFlowCheckDTO checkDTO = WorkFlowCheckDTO.getWorkFlowCheckDTO(
                temp.getFlow_current_node_id(), // 当前节点id
                temp.getFlow_json(), // 流程json
                dto.getWf_check_opinion(), // 审批意见
                dto.getWf_check_sign_url(), // 审批签名链接
                JSONObject.toJSONString(temp) // 旧数据留存
        );

        // 审批
        return isPass ? wfu.ToNext(checkDTO) : wfu.ReturnBack(checkDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean returnBack(ReimburseApplyCheckDTO dto) {
        // 驳回
        int flowResult = passAndBack(dto, false, false);
        if (flowResult != 1) throw new CommonException("驳回失败，请联系管理员！");
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(Long id) {
        int flowResult = deleteAndActualDel(id, false);
        if (flowResult != 1) throw new CommonException("删除失败，请联系管理员！");
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean actualDelete(Long id) {
        int flowResult = deleteAndActualDel(id, true);
        if (flowResult != 1) throw new CommonException("彻底删除失败，请联系管理员！");
        return true;
    }

    // 删除 和 彻底删除 抽出相同代码
    private int deleteAndActualDel(Long id, boolean isActual) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<ReimburseApply, ReimburseApplyMapper>(id, userId, ReimburseApply.class);

        // 流程id
        Long wfData_id = wfu.getWfDataId(id);

        return isActual ? wfu.ActualDelete(wfData_id) : wfu.Delete(wfData_id);
    }
}
